import 'dart:io';

import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_crashlytics/firebase_crashlytics.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:firebase_performance/firebase_performance.dart';
import 'package:firebase_plugin/core/firebase_analytics_utils.dart';
import 'package:firebase_plugin/core/firebase_performance_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // If you're going to use other Firebase services in the background, such as Firestore,
  // make sure you call `initializeApp` before using other Firebase services.
  // await Firebase.initializeApp(
  //   options: DefaultFirebaseOptions.currentPlatform,
  // );

  // Log.i(
  //     'firebase message Handling a background message ${message.data.toString()}');
}

class FCM {
  //保存taken
  static var token = "";

  static Future init(
      {required Function(String token) onToken,
      required Function(dynamic jump) onJump,
      required Function(String firebaseId) onFirebaseId}) async {
    if (!kIsWeb) {
      late AndroidNotificationChannel channel;

      /// Initialize the [FlutterLocalNotificationsPlugin] package.
      late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
      channel = const AndroidNotificationChannel(
          'high_importance_channel', // id
          'High Importance Notifications',
          description: 'This channel is used for important notifications.',
          importance: Importance.high // title
          );
      flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
      // initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
      // const AndroidInitializationSettings initializationSettingsAndroid =
      AndroidInitializationSettings('ic_launcher');
      // initialise the plugin. app_icon needs to be a added as a drawable resource to the Android head project
      await Firebase.initializeApp(
          // options: DefaultFirebaseOptions.currentPlatform,
          );

      FirebasePerformanceUtils.init();

      //
      if (Platform.isMacOS) {
        // Force disable Crashlytics collection while doing every day development.
        // Temporarily toggle this to true if you want to test crash reporting in your app.
        await FirebaseCrashlytics.instance
            .setCrashlyticsCollectionEnabled(false);
        FirebasePerformance.instance.setPerformanceCollectionEnabled(false);
        FirebaseAnalytics.instance.setAnalyticsCollectionEnabled(false);
      }
      // else {
      //   // Handle Crashlytics enabled status when not in Debug,
      //   // e.g. allow your users to opt-in to crash reporting.
      // }

      FirebaseMessaging.onBackgroundMessage(
          _firebaseMessagingBackgroundHandler);
      await flutterLocalNotificationsPlugin
          .resolvePlatformSpecificImplementation<
              AndroidFlutterLocalNotificationsPlugin>()
          ?.createNotificationChannel(channel);

      /// Update the iOS foreground notification presentation options to allow
      /// heads up notifications.
      await FirebaseMessaging.instance.requestPermission(
        alert: true,
        announcement: false,
        badge: true,
        carPlay: false,
        criticalAlert: false,
        provisional: false,
        sound: true,
      );
      // await FirebaseMessaging.instance
      //     .setForegroundNotificationPresentationOptions(
      //   alert: true,
      //   badge: true,
      //   sound: true,
      // );
      FirebaseMessaging.instance.getToken().then((value) {
        print("firebase token:$value");
        String registrationToken = value.toString();
        onToken(registrationToken);
        //TODO wangchao
        // token = registrationToken;
        // ChatUserInfoModel.imPushToken = token;
        // var bodyToken = {"registrationToken": token};
        // MicHttpConfig.post(Api.fcmToke,
        //     body: bodyToken, success: (t) {}, fail: (code, t) {});
      }).catchError((err) {
        print('onerr firbase err:$err');
      }).onError((error, stackTrace) {
        print('onerr firbase:$error');
      });
      FirebaseMessaging.onMessage.listen((event) {
        var notification = event.notification;
        var android = event.notification?.android;
        if (notification != null && android != null && !kIsWeb) {
          flutterLocalNotificationsPlugin.show(
              notification.hashCode,
              notification.title,
              notification.body,
              NotificationDetails(
                  android: AndroidNotificationDetails(
                channel.id,
                channel.name,
                icon: 'ic_launcher',
              )));
          print("firebase message:${event.notification?.title}");
        }
      });
      FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
        print(
            'firebase message onMessageOpenedApp event data: ${message.data} : ${message.messageId}');
        if (message.data.containsKey("jump")) {
          onJump(message.data["jump"]);
        }
      });
      FirebasePerformance.instance.setPerformanceCollectionEnabled(true);
      FirebaseAnalyticsUtils().init().then((value) {
        onFirebaseId(value);
      });
    } else {
      // await Firebase.initializeApp(
      //   options: DefaultFirebaseOptions.currentPlatform,
      // );
      // FirebaseMessaging messaging = FirebaseMessaging.instance;
      // // use the returned token to send messages to users from your custom server
      // String? token = await messaging.getToken(
      //   vapidKey:
      //       "BK05I7JlkVMnDhjUlXnzTeN3e7cpvVRFn1AeM9eJq-ltH5aJLmRQ8HMwkNXzHXlooR_xGC-V5nKS7FQEOzttZzk",
      // );
      // Log.i('firebase message web fcm token:$token');
    }
  }
}
